package com.umeox.moto.watch.fitness.utils;


import android.text.TextUtils;
import android.util.Log;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.utils.DateUtils;
import com.umeox.moto.watch.fitness.bean.SportChallengeDetail;
import com.umeox.moto.watch.fitness.db.AppDatabase;
import com.umeox.moto.watch.fitness.db.model.TodayChallenge;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {


    public static final String EXTRA_KEY_ALARM = "alarm_detail";
    public static final String EXTRA_KEY_ID = "id";
    public static final String EXTRA_KEY_AUTO = "auto";
    public static final String EXTRA_KEY_REPEAT_EXPRESSION = "alarm_repeat_expression";

    public static final String ALARM_NOREPEAT_EXP = "0000000";
    public static final String ALARM_EVERYDAY_REPEAT_EXP = "1111111";

    /**
     * 判断服务器闹钟时间格式是否正确 HH:mm
     */
    public static boolean is24HourFormatTime(String alarmTimeStr) {
        if (TextUtils.isEmpty(alarmTimeStr)) {
            return false;
        }
        String rexp = "^(([0-1][0-9])|2[0-3]):[0-5][0-9]$";
        Pattern pat = Pattern.compile(rexp);
        Matcher mat = pat.matcher(alarmTimeStr);
        return mat.matches();
    }

    /**
     * 判断时间段，重复周期格式是否正确
     * 正确格式：1100011  7个字节长度，只允许0或者1
     */
    public static boolean isInvalidRepeatExpression(String repeatExpression) {
        String rexp = "[0-1]{7}";
        return Pattern.compile(rexp).matcher(repeatExpression).matches();
    }


    //重复周期只有星期天
    private static final String ONE_SUNDAY_EXP = "1000000";


    /**
     * Combine a list of strings in an <code>Object[]</code> into a single
     * string.
     *
     * @param list non-null; the strings to combine
     * @return non-null; the combined form
     */
    public static String combineStrings(CharSequence[] list, char separator) {
        int listLength = list.length;

        if (listLength == 0) {
            return "";
        } else if (listLength == 1) {
            return (String) list[0];
        }

        int strLength = 0;

        for (Object o : list) {
            strLength += ((String) o).length();
        }

        StringBuilder sb = new StringBuilder(strLength);
        for (Object temp : list) {
            if (temp == null || TextUtils.isEmpty(temp.toString())) {
                continue;
            }
            sb.append(temp).append(separator);
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static List<SportChallengeDetail> getSportChallengeList() {
        return getSportChallengeList(true);
    }

    public static List<SportChallengeDetail> getSportChallengeList(boolean withoutLater) {
        ArrayList<SportChallengeDetail> list = new ArrayList<>();
        List<TodayChallenge> challenges = AppDatabase.Companion.get().todayChallengeDao().loadAllChallenge();
        if (challenges != null && !challenges.isEmpty()) {
            for (TodayChallenge temp : challenges) {
                SportChallengeDetail challengeDetail = SportChallengeDetail.convertFromValues(temp);
                if (challengeDetail != null) {
                    long tempTime = getNextAlarmTimeMillis(challengeDetail);
                    if (tempTime > 0) {
                        challengeDetail.alarmTimeInMillis = tempTime;
                    }
                    list.add(challengeDetail);
                }
            }
        }
        Logger.i("获取运动挑战：" + list);
        return list;
    }

    /**
     * 获取下次运动挑战提醒的时间
     */
    public static SportChallengeDetail getNextSportChallengeDetail(List<SportChallengeDetail> sportChallengeDetailList) {
        if (sportChallengeDetailList == null || sportChallengeDetailList.isEmpty()) {
            Logger.w("运动挑战列表为空");
            return null;
        }
        List<SportChallengeDetail> temp = new ArrayList<>();
        for (SportChallengeDetail detail : sportChallengeDetailList) {
            if (detail.alarmTimeInMillis > System.currentTimeMillis()) {
                temp.add(detail);
            }
        }

        SportChallengeDetail nextAlarm = null;
        for (SportChallengeDetail detail : temp) {
            Logger.i("每个运动挑战，重复周期中距离现在最近的时间：" + DateUtils.formatDateTime(detail.alarmTimeInMillis));
            if (nextAlarm == null
                    || nextAlarm.alarmTimeInMillis > detail.alarmTimeInMillis) {
                nextAlarm = detail;
            }
        }
        return nextAlarm;
    }

    /**
     * 获取闹钟具体的响铃时间
     *
     * @param detail 闹钟对象
     */
    public static long getNextAlarmTimeMillis(SportChallengeDetail detail) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, detail.getHour());
        cal.set(Calendar.MINUTE, detail.getMinute());
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        final long timeInMillis = cal.getTimeInMillis();
        if (timeInMillis > System.currentTimeMillis()) {
            return timeInMillis;
        }
        cal.add(Calendar.DAY_OF_MONTH, 1);
        return cal.getTimeInMillis();
    }


    /**
     * 获取12小时制格式
     *
     * @param time   10:00、23:22格式
     * @param locale
     * @return 返回 10:00 AM、11:22 PM格式
     */
    public static String to12HourFormat_AM_PM(String time, Locale locale) {
        try {
            SimpleDateFormat hourFormat = new SimpleDateFormat("hh:mm", locale);
            return DateFormat
                    .getTimeInstance(DateFormat.SHORT, locale)
                    .format(hourFormat.parse(time));
        } catch (ParseException e) {
            Log.e("DATEUTILS", "to12HourFormat_AM_PM", e);
        }
        return time;
    }

    /**
     * 获取12小时制格式
     *
     * @param time   10:00、23:22格式
     * @param locale
     * @return 返回 10:00、11:22格式
     */
    public static String to12HourFormat(String time, Locale locale) {
        try {
            SimpleDateFormat hourFormat = new SimpleDateFormat("hh:mm", locale);
            return hourFormat.format(hourFormat.parse(time));
        } catch (ParseException e) {
            Log.e("DATEUTILS", "to12HourFormat: ", e);
        }
        return time;
    }
}
